import common from "../../../utils/common"
const app = getApp()
const db = wx.cloud.database()
let audio = wx.createInnerAudioContext({
    useWebAudioImplement: true
})
let m = 0, // 单词起始位置
    n = 5, // 默认学习条数，初始值为5
    array = [], //存放单词数据
    concatList = [],
    idx = 0, //单词初始下标，默认0
    today = new Date(), // 对已学单词加入年月日
    year = today.getFullYear(),
    mon = today.getMonth() + 1,
    day = today.getDate(),
    // 两个单词本以学的数量，通过缓存判断当前单词本，点击next加一，接着存入缓存中
    a = 0,
    rvw_arr = [],
    newArr = {},
    today_cnt = 0,
    time = '',
    current = 0, // 当前单词索引
    autoPlay = wx.getStorageSync('autoplay'),
    lineData = {},
    delList = [],
    addWordList = [],
    wordName = {},
    cptword = {},
    taskNum = 0,
    addStarList = []

Page({
    tartPageX: 0,
    data: {
        DataList: [],
        addList: [],
        lyricShow: false,
        showNot: true,
        popShowNot: true,
        searchShow: false,
        showDef: false,
        definition: "",
        starNot: true,
        is_play: false,
        indicatorDots: true,
        vertical: false,
        circular: false,
        duration: 800,
        delNot: true,
        inputText: "",
    },

    getDef: function () { // 释义显示
        this.setData({
            showDef: !this.data.showDef
        })
    },

    clickShow: function () { // 歌词显示
        this.setData({
            lyricShow: !this.data.lyricShow
        })
    },

    async inputShow() {
        new Promise(() => {
            this.setData({
                searchShow: !this.data.searchShow
            })
            this.animate('.search', [{
                width: '0',
                height: "0"
            }, {
                width: "170px",
                height: '35px'
            }], 400)
        })

    },

    async onLoad(options) {
        console.log("当前current", current)
        time = year + '-' + mon + '-' + day
        // 为自动打卡前提
        if (!wx.getStorageSync('punchCard') || wx.getStorageSync('punchCard').today_time !== time){
            await wx.setStorageSync('punchCard', { 
                punchCard: 'noCard',
                today_time: time
            })
        }
        
        lineData = wx.getStorageSync('lineData')

        if (lineData.length > 0 && lineData[lineData.length - 1].time == time) {
            today_cnt = lineData[lineData.length - 1].today_cnt //获取已缓存的today_cnt
            console.log('today_cnt', today_cnt)
            today_cnt += 1
        } else {
            console.log('没走到这一步')
            today_cnt += 1
        }

        console.log('当前cnt', today_cnt)

        m = 0
        n = 5
        idx += 1 // 每次进入页面时，单词起始下标归为0，避免数据残留
        if (options.taskNum) {
            // 重置学习条数
            taskNum = parseInt(options.taskNum)
            n = parseInt(options.taskNum)
        }
        // 必须有书籍缓存，才会进入当前页面，所以无需判断是否有缓存
        let currBook = wx.getStorageSync('currBook')
        console.log('当前book', currBook)
        this.type = currBook.type
        // 根据当前书籍的类型type，获取已学习进度
        if (currBook.type == 'cet4') {
            if (wx.getStorageSync('cet4Progress')) {
                m = wx.getStorageSync('cet4Progress')
                a = wx.getStorageSync('cet4Progress') // 用a缓存学习进度
            }
        } else if (currBook.type == 'cet6') {
            if (wx.getStorageSync('cet6Progress')) {
                m = wx.getStorageSync('cet6Progress')
                a = wx.getStorageSync('cet6Progress')
            }
        } else if (currBook.type == 'kaoyan') {
            if (wx.getStorageSync('kaoyanProgress')) {
                m = wx.getStorageSync('kaoyanProgress')
                a = wx.getStorageSync('kaoyanProgress')
            }
        }
        // 根据值传递，获取对应数据库数据，此时数据从下标m开始
        // 此时的下标是进入页面的初始下标0，即idx为0，获取数据
        // 没有学习记录，从0开始获取。有记录，在上次学习的最后一个单词数量上+1后，开始获取数据
        // 初次进入页面，此处只需直接传值，不需要改变m的值，避免影响setdata()方法中的数据处理
        array = await this.getinfo(m == 0 ? 0 : m + 1, n, currBook.type)
        concatList = array
        // console.log('array', array, '初始concatListt', concatList)
        // 渲染数据
        // 初次进入页面，发生跳数据问题。也就是m值此时不可改变
        this.setdata(m, currBook.type, concatList)
    },

    async next(e) {
        current = e.detail.current
        idx = current + 1
        let {
            DataList
        } = this.data

        console.log('调用了animationfinish', idx, 'DataList', DataList)
        // 有音频则播放没有则停止播放当前音频并且查询音频状态
        concatList[current].address ? this.playmusic(concatList[current].address) : this.stopAudio()

        this.setData({ //  反应掉帧
            showDef: false
        })
        // 满足打卡条件
        if (idx == taskNum && wx.getStorageSync('punchCard').punchCard == 'noCard') { 
            wx.setStorageSync('punchCard', {
                punchCard: "canCard",
                today_time: time
            })
            await common.autoCard(time, year, mon, day)
        }

        // 数据长度5，下标应从0到4，下标为5时需要弹框。即下标值idx≥数据长度，弹框。数据长度同时也是学习的条数
        if (idx >= concatList.length) {
            // 用户确定继续，下标归0；单词新的起始位置m，为当前位置m+学习条数n，即m+=n，重置后开始获取新的数据，并赋值到array
            m += n
            array = await this.getinfo(m + 1, n, this.type)
            concatList = concatList.concat(array)
            console.log('确认里的DataList', concatList)
            // 渲染数据
            this.setdata(m, this.type, concatList)
            // this.next('', current + 1) // 确认增加数据后跳转下一个数据
            console.log('加入数组的数据为', array, idx, m, n)

        }
        // 下标未溢出
        else {
            // 下标值未超过学习条数时，继续渲染数据。m从0开始
            console.log('next中，m的值为：', m)
            this.setdata(m, this.type, concatList)
        }

        // 更新学习进度，分当前、新增
        let arrLine = wx.getStorageSync('lineData'),
            data = [],
            Tod_flag = true,
            new_data = {
                time,
                today_cnt
            };
        if (arrLine.length) { // 判断是否为当天数据
            arrLine.forEach(item => {
                if (item.time == new_data.time) {
                    item.today_cnt = new_data.today_cnt
                    Tod_flag = false;
                }
                data.push(item);
            })
        }
        if (Tod_flag) {
            data.push(new_data);
        }
        // arr_data = data
        wx.setStorageSync('lineData', data);

    },

    touchStart(e) {
        this.startPageX = e.changedTouches[0].pageX;
    },

    touchEnd(e) { // 左滑滑动跳转
        const moveX = e.changedTouches[0].pageX - this.startPageX;
        // console.log(moveX > 0 ? '右滑' : '左滑', moveX)
        if (moveX <= -60) {
            wx.navigateTo({
                url: "/pages/dictionary/wordDetail/wordDetail?content=" + concatList[current].content + '&id=' + concatList[current]._id
            })
        }
    },

    /**
     * 页面添加生词本
     */
    async pageAddWord() {
        let {
            content,
            _id
        } = concatList[current]
        new Promise(() => {
            addWordList.push(content)
            this.setData({
                showNot: false,
            })
            common.addNoteWord(concatList[current], content, _id)
        })
    },

    /**
     * 组件添加yp
     */
    async addvdo(){
        await common.poppupAddVedio(cptword.content,cptword.id)
    },

    /**
     * 组件添加生词本
     */
    cptAddWord() {
        let {
            content,
            _id
        } = wordName
        this.setData({
            popShowNot: false,
        })
        this.addWord('', content, _id)
    },

    // 页面取消生词
    async pageCancelWord() {
        new Promise(() => {
            this.setData({
                showNot: true
            })
            addWordList.forEach((item, index) => {
                if (item == concatList[current].content) {
                    addWordList.splice(index, 1);
                }
            });
            common.delNoteWord(wordName._id)
        })
    },

    cptCancelWord(e, _id) {
        common.delNoteWord(wordName._id)
        this.setData({
            popShowNot: true
        })
    },

    // 单词斩
    delWord() {
        delList.push(concatList[current].content)
        this.setData({
            delNot: false
        })
        console.log('delList', delList)
    },

    canDelWord() {
        delList.forEach((item, index) => {
            if (item == concatList[current].content) {
                delList.splice(index, 1);
            }
        });
        this.setData({
            delNot: true
        })
    },

    read: function () {
        console.log('read', current)
        this.playAudioByWord(concatList[current].content)
    },

    popupRead() {
        this.playAudioByWord(wordName.content)
    },

    onReady: function () {
        // 绑定组件id，用于后面调用指定id组件内的方法
        this.component = this.selectComponent("#_popup")
    },

    /**
     * 根据单词，设置音频地址并播放。同时监听音频停止事件
     */
    playAudioByWord(word) {
        audio.src = `https://dict.youdao.com/dictvoice?audio=${word}&type=2`
        audio.play()
        audio.onStop(res => {
            // 清空音频链接
            audio.src = ''
        })
    },

    // 收藏单词
    async star() {
        new Promise(() => {
            let {
                content,
                _id
            } = concatList[current]
            addStarList.push(content)
            this.setData({
                starNot: false,
            })
            common.addStar(content, _id)
        })
    },

    // 取消收藏单词
    async cancelStar() {
        new Promise(() => {
            this.setData({
                starNot: true,
            })
            addStarList.forEach((item, index) => {
                if (item == concatList[current].content) {
                    addStarList.splice(index, 1);
                }
            });
            common.cancelStar(concatList[current]._id)
        })

    },

    /**
     * 1. 弹出组件
     * 2. 查询单词 
     */
    async showPopup(e) {
        // this.cptstopAudio()
        audio.stop()
        let {
            inputText
        } = this.data
        inputText = e.detail.value
        if (inputText) {
            await common.qureyWordAuido(this, inputText)
            this.clearInput()
        }

        cptword = await wx.getStorageSync('queryWord')
        console.log(cptword)

    },

    /**
     * 清空输入框
     */
    clearInput() {
        this.setData({
            inputText: '',
            searchShow: false
        })
    },

    /**
     * 停止音频文件
     */
    stopAudio() {
        audio.stop()
        audio.src = '' // 将地址置空
        // this.music("", concatList[current].address)
    },

    //播放
    async playmusic(address) {
        const {
            is_play
        } = this.data
        if (is_play) {
            audio.pause();
            this.setData({
                is_play: false
            })
            console.log("暂停播放")
        } else if (!is_play) {
            audio.src = address
            audio.play();
            this.setData({
                is_play: true
            })
            console.log("继续播放")
        }
    },

    // 判断单词状态
    async music(e, address) {
        address ? address : concatList[current].address
        if (address || concatList[current].address) {
            this.playmusic(address || concatList[current].address)
        } else { // 减少用户在学习页面操作次数，将加音频工作移到详情页面
            await common.qureyAudioStatus(concatList[current].content)
        }
    },

    // 判断播放设置
    async queryPlaySet(audioAddress) {
        console.log('调用了queryPlaySet', autoPlay)
        if (audioAddress.address && autoPlay) { // 判断是否能自动播放
            this.playmusic(audioAddress.address)
        } else if (!audioAddress.address && autoPlay) { // 如果没此字段和自动播放设置就查询审核音频库
            this.music("", audioAddress.address)
        }
    },

    cptstopAudio() { // 暂停播放
        common.cptstopAudio()
    },

    // 获取数据(利用云函数来获取)
    async getinfo(m, n, type) {
        wx.showLoading({
            title: '获取中',
        })

        // 调用getDictWord云函数，并传入m,n值
        let {
            result
        } = await wx.cloud.callFunction({
            name: 'getDictWord',
            data: {
                m,
                n,
                type
            }
        })

        new Promise(() => { // 单词加粗，提取中文翻译并加样式 TODO
            result.forEach(item => {
                if (item.lyric) {
                    common.processLyric(item)
                }
            });
        })
        wx.hideLoading()
        console.log('处理后的数据：', result)
        return result
    },
    // 渲染数据
    async setdata(m, type, concatList) {
        console.log('此时的m', m, "此时的current", current)
        let content = concatList[current].content
        let _id = concatList[current]._id
        console.log('存入的数组：', content, _id)
        console.log('delList', delList)
        new Promise(() => {
            // let unique = (uni_arr) => { // 列表去重
            //     return Array.from(new Set(uni_arr))
            // }
            // delList = unique(delList);
            delList.includes(content) ? this.setData({
                delNot: false
            }) : this.setData({
                delNot: true
            })
            addWordList.includes(content) ? this.setData({
                showNot: false
            }) : this.setData({
                showNot: true
            })
            addStarList.includes(content) ? this.setData({
                starNot: false
            }) : this.setData({
                starNot: true
            })

        })

        if (content) { // 学习结束添加到复习本
            rvw_arr.push({
                content,
                _id
            })
        }
        console.log('去重前的值：', rvw_arr)
        let deWeightThree = () => { // 键值对去重
            let map = new Map();
            for (let item of rvw_arr) {
                if (!map.has(item.content)) {
                    map.set(item.content, item);
                }
            }
            return [...map.values()];
        }
        newArr = deWeightThree();
        console.log('去重后的值：', newArr)

        this.queryPlaySet(concatList[current]) // 查询播放设置

        this.setData({
            DataList: concatList
        })
        // console.log('setData里的concatList', concatList)
    },

    /**监听用户退出当前页面,数据库缓存数据 */
    async onUnload() { // TODO
        current = 0
        // 缓存学习进度
        a = a + current + 2 // 原始值 + 当前页面索引 + 1 + 
        console.log('设置数据a后', a)
        // console.log(`加载第${idx}个单词`)
        // return
        new Promise(() => {
            // 更新用户表表
            common.upUserData()
            if (this.type == 'cet4') { // 加入缓存
                wx.setStorageSync('cet4Progress', a)
            } else if (this.type == 'cet6') {
                wx.setStorageSync('cet6Progress', a)
            } else if (this.type == 'kaoyan') {
                wx.setStorageSync('kaoyanProgress', a)
            }
            // 单词本去除被斩单词
            if (delList){
                newArr = newArr.filter((item) => {
                    return delList.indexOf(item.content) < 0
                })
            }
            console.log(newArr)
            // 将已学单词加入复习本
            if (newArr.length > 0) {
                db.collection('reviewList').add({
                        data: {
                            flag: false,
                            year: year,
                            mon: mon,
                            day: day,
                            newArr
                        }
                    })
                    .then(res => {
                        rvw_arr = []
                        newArr = {}
                        console.log('用户退出操作', newArr)
                    })
            }
        })
        audio.stop() // 音频停止播放
        // 退出当前界面更新数据
        // console.log('arr_data', arr_data)

    }
})